
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _ =db.command
async function getSkuInfo(body: any) {
  let whereJson = {deleted:0,_id:body.id}
  let skuInfo = await nw.db.findByWhereJson({
    dbName:"skuInfo",
    whereJson:whereJson
  })
  if (!nw.util.isNull(skuInfo)){
    skuInfo.id = skuInfo._id
    //1.skuImagesList
    skuInfo.skuImagesList = await nw.db.findListByWhereJson({
      dbName:"skuImage",
      whereJson:{deleted:0,skuId:skuInfo._id}
    })
    //2.skuPosterList
    skuInfo.skuPosterList = await nw.db.findListByWhereJson({
      dbName:"skuPoster",
      whereJson:{deleted:0,skuId:skuInfo._id}
    })
    //3.skuAttrValueList
    skuInfo.skuAttrValueList = await nw.db.findListByWhereJson({
      dbName:"skuAttrValue",
      whereJson:{deleted:0,skuId:skuInfo._id}
    })
  }
  return Promise.resolve(skuInfo)
}

/**
 * 辅助函数
 * @param target
 */
function setRuleDesc(target: {
  activityId: any;
  benefitAmount: any;
  conditionAmount: any;
  id: any;
  conditionNum: any;
  activityType: any;
  benefitDiscount: any;
  ruleDesc:any
}) {
  if (target.activityType===0){
    target.ruleDesc = `满${target.conditionAmount}元减${target.benefitAmount}元`
  }else {
    target.ruleDesc = `满${target.conditionNum}件打${target.benefitDiscount}折`
  }
}
async function getActivityRuleList(body: any) {
  //1.查询activitySku
  let activitySku = await nw.db.findListByWhereJson({
    dbName:"activitySku",
    whereJson:{deleted:0,skuId:body.id}
  })
  if (nw.util.isNull(activitySku)||!nw.util.isArray(activitySku)||activitySku.length===0){
    return Promise.resolve([])
  }
  let activityIds = activitySku.map(item=>item.activityId)
  //2.查询活动
  let activity = await nw.db.findListByWhereJson({
    dbName:"activityInfo",
    whereJson:{deleted:0,_id:_.in(activityIds)}
  })
  if (nw.util.isNull(activity)||!nw.util.isArray(activity)||activity.length===0){
    return Promise.resolve([])
  }
  //构建返回结果
  let activityList = []
  for (let i = 0; i < activity.length; i++) {
    let each = {
      activityId:activity[i]._id,
      activityType:activity[i].activityType
    }
    activityList[i] = each
  }
  //3.查询activityRule
  let activityRules = await nw.db.findListByWhereJson({
    dbName:"activityRule",
    whereJson:{deleted:0,activityId:_.in(activityIds)}
  })
  if (nw.util.isNull(activityRules)||!nw.util.isArray(activityRules)||activityRules.length===0){
    return Promise.resolve(activityList)
  }

  let result = []
  let ruleMap = new Map()
  for (let i = 0; i < activityRules.length; i++) {
    let activityRule = activityRules[i]
    if (ruleMap.has(activityRule.activityId)){
      ruleMap.get(activityRule.activityId).push(activityRule)
    }else {
      ruleMap.set(activityRule.activityId,[activityRule])
    }
  }

  for (let i = 0; i < activityList.length; i++) {
    let each = activityList[i]
    if (ruleMap.has(each.activityId)){
      let rus = ruleMap.get(each.activityId)
      for (let j = 0; j < rus.length; j++) {
        let ru  = rus[i]
        let target = {
          id:ru._id,
          activityType:each.activityType,
          activityId:each.activityId,
          conditionAmount:ru.conditionAmount,
          conditionNum:ru.conditionNum,
          benefitAmount:ru.benefitAmount,
          benefitDiscount:ru.benefitDiscount,
          ruleDesc:""
        }
        setRuleDesc(target)
        result.push(target)
      }
    }
  }

  return Promise.resolve(result)
}

async function getCouponInfoList(body: any, userId: any) {
  //1.查询未使用couponUse
  let couponUse = await nw.db.findListByWhereJson({
    dbName:"couponUse",
    whereJson:{deleted:0,userId:userId,couponStatus:1}
  })
  if (nw.util.isNull(couponUse)||!nw.util.isArray(couponUse)||couponUse.length===0){
    return Promise.resolve([])
  }
  //2.查询符合当前ID的优惠券数据
  let skuInfo = await nw.db.findById({
    dbName:"skuInfo",
    id:body.id
  })
  if (nw.util.isNull(skuInfo)){
    return Promise.resolve([])
  }
  //查询对应的优惠券即可
  let couponIds = couponUse.map(item=>item.couponId)
  //查询对应的使用规则
  let couponRanges = await nw.db.findListByWhereJson({
    dbName:"couponRange",
    whereJson:{deleted:0,couponId:_.in(couponIds)}
  })
  let allowedCouponIds = []
  for (let i = 0; i < couponRanges.length; i++) {
    switch (couponRanges[i].rangeType) {
      case 1:
        allowedCouponIds.push(couponRanges[i].couponId)
        break
      case 2:
        if (skuInfo.categoryId===couponRanges[i].rangeId){
          allowedCouponIds.push(couponRanges[i].couponId)
        }
        break
      case 3:
        if (skuInfo._id===couponRanges[i].rangeId){
          allowedCouponIds.push(couponRanges[i].couponId)
        }
        break
    }
  }

  if (allowedCouponIds.length===0){
    return Promise.resolve([])
  }

  let coupons = await nw.db.findListByWhereJson({
    dbName:"couponInfo",
    whereJson:{deleted:0,_id:_.in(allowedCouponIds)}
  })
  if (coupons.length===0){
    return Promise.resolve([])
  }
  for (let i = 0; i < coupons.length; i++) {
    coupons[i].id = coupons[i]._id
    coupons[i].couponStatus = 1
  }
  return Promise.resolve(coupons)
}

export default async function (ctx: FunctionContext) {
  let body = ctx.body
  let userId = ctx.user.admin
  //1.参数校验
  if (nw.util.isNull(body.id)){
    return fail("参数不合法，请选择正确的商品")
  }
  //2.初始化返回参数
  let result = {
    skuInfoVo:{},
    couponInfoList:[],
    activityRuleList:[]
  }

  //查询skuInfo
  const p1 = getSkuInfo(body)
  const p2 = getActivityRuleList(body)
  const p3 = getCouponInfoList(body,userId)

  let [skuInfo,activityRuleList,couponInfoList] = await Promise.all([p1,p2,p3])
  if (nw.util.isNull(skuInfo)){
    await nw.db.update({
      dbName:"skuInfo",
      whereJson:{_id:skuInfo._id},
      dataJson:{clickCount:skuInfo.clickCount+1}
    })
  }
  result.skuInfoVo = skuInfo
  result.activityRuleList = activityRuleList
  result.couponInfoList = couponInfoList
  return ok(result)
}
